package Client;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.LinkedList;

import General.ClientEventInterface;
import General.ClientNotificatorInterface;
import General.Product;


public class ClientEventHandler implements ClientEventInterface, Serializable {

	private static final long serialVersionUID = 1L;
	private ClientNotificatorInterface fClientNotificator;
	private LinkedList<String> fNotifications;
	private int fClientId;
	
	public ClientEventHandler(ClientNotificatorInterface clientNotificator, int clientId) {
		fClientNotificator = clientNotificator;
		fNotifications = new LinkedList<String>();
		fClientId = clientId;
	}

	public void notification(Product product, int state) {
		fNotifications.add("The state changed to " + Product.getStateName(state) + " for the product with id " + product.getId());
		this.sentNotifications();
	}
	
	private void sentNotifications() {
		if (fNotifications.size() >= 3) {
			Iterator<String> it = fNotifications.iterator();
			while (it.hasNext()) {
				try {
					fClientNotificator.notification(it.next());
					it.remove();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public int getClientId() {
		return fClientId;
	}
}
